package com.example.demo.controller;

import com.example.demo.constant.Constant;
import com.example.demo.model.ReturnResult;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public ReturnResult<Boolean> login(UserInfo userInfo, HttpSession session){
        log.info("/user/login接收到参数 UserInfo: {}", userInfo);
        // 1. 校验参数
        String userName = userInfo.getUserName();
        String password = userInfo.getPassword();
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            //log.info("/user/login: 用户名或密码为空");
            return ReturnResult.failure("用户名或密码为空", false);
        }
        // 2. 校验用户是否存在
        UserInfo dataSourceUserInfo = userService.queryUserInfoByName(userName);
        if(dataSourceUserInfo == null){
            //log.info("/user/login: 用户不存在");
            return ReturnResult.failure("用户不存在", false);
        }
        // 3. 检验用户密码是否正确
        if(!password.equals(dataSourceUserInfo.getPassword())){
            //log.info("/user/login: 密码错误");
            return ReturnResult.failure("密码错误", false);
        }

        // 4. 保存用户登录信息
        session.setAttribute(Constant.SESSION_KEY_USERINFO, userInfo);
        return ReturnResult.success(true);
    }
}
